<script setup lang="ts">
import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { userAssignRole, userRoleQuery } from '#/api/system/user';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { assignRoleModalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
      class: 'w-full',
    },
  },
  schema: assignRoleModalSchema(),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Modal, modalApi] = useVbenModal({
  class: 'w-[400px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData();
    if (id) {
      try {
        const res = await userRoleQuery(id);
        const list: number[] = [];
        const options = res.map((item) => {
          if (item.checked) {
            list.push(item.id);
          }
          return { label: item.roleName, value: item.id };
        });
        formApi.updateSchema([
          {
            componentProps: {
              options,
            },
            fieldName: 'roleIdList',
          },
        ]);
        formApi.setValues({ id, roleIdList: list });
      } catch (error) {
        console.error(error);
      }
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    const { roleIdList, id } = cloneDeep(await formApi.getValues());

    try {
      await userAssignRole({ roleIdList, userId: id });
    } catch (error) {
      console.error(error);
    }
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <Modal title="分配角色">
    <BasicForm />
  </Modal>
</template>
